package com.ctgu.project01.interceptor;

import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * @ClassName TokenInterceptor
 * @Author Alex2
 * @Date 2025/2/26 11:02
 **/
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("usersEntity");
        if (user == null) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            errorResponse(response);
            return false;
        }
        return true;
    }

    public void errorResponse(HttpServletResponse response) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", "token无效");
        map.put("code", HttpServletResponse.SC_UNAUTHORIZED);
        map.put("data", null);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }
}
